/**
 * 
 */
package data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;

import domain.Article;
import domain.Computer;
import domain.Supplier;

/**
 * @author grupo22
 *
 */
public class JDBCArticleDAO implements IArticleDAO {
	
	public Collection selectAllArticles(){
		Collection result = new LinkedList();
		
		Connection con = ConnectionManager.getInstance().checkOut();
		PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
        	String sql = "SELECT * FROM Article;";
        	stmt = con.prepareStatement(sql);
            
            rs = stmt.executeQuery();

            while (rs.next()) {
            	String type = rs.getString("type");
                String code = rs.getString("code");
                String contestCode = rs.getString("contestCode");
                Article a = new Article(type, code, contestCode);
                result.add(a);
            }
        } catch (SQLException e) {
            System.out.println("Message: Fallo en selectAllArticles " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
        	ConnectionManager.getInstance().checkIn(con);
        	try {
                    if (rs != null)
                            rs.close();
                    if (stmt != null)
                            stmt.close();
            } catch (SQLException e) {}
        }

		return result;
	}
	/* (non-Javadoc)
	 * @see data.IArticleDAO#select(java.sql.Connection, java.lang.String)
	 */
	@Override
	public Article select(Connection con, String oid) {
		String sql = "SELECT * FROM Article WHERE (OIDArticle = ? )";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        Article a = null;

        try {
            stmt = con.prepareStatement(sql);
            stmt.setString(1, oid);

            rs = stmt.executeQuery();

            rs.next();
            String type = rs.getString("type");
            String code = rs.getString("code");
            String contestCode = rs.getString("contestCode");
            a = new Article(type, code, contestCode);
            
        } catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) { }
        }
        return a;
	}

}
